import json
import os
from time import time, sleep
from typing import Literal

from pynput import mouse, keyboard
from pynput.keyboard import  KeyCode

from models.config import Config
from utils.paths import KM_PATH


class AutoKM:
    DOUBLE_CLICK_INTERVAL = 0.3

    def __init__(self):
        self.current_index = 0
        self.is_start_record = False
        self.ctr = []
        self.config = Config.load()

    def start_ctr(self):
        """
        准备开始记录鼠标轨迹
        :return:
        """
        print("按下 `R` 键开始记录鼠标轨迹，再次按下 `R` 键结束记录。")

        # 获取当前最大的文件索引
        for fn in os.listdir(KM_PATH):
            if fn.startswith('ctr_') and fn.endswith('.txt'):
                index = int(fn.split('_')[1].split('.')[0])
                if index > self.current_index:
                    self.current_index = index

        def on_press(key):
            if isinstance(key, KeyCode) and key.char == self.config.mouseRecordShortcut:
                if not self.is_start_record:
                    self.current_index += 1
                    self.is_start_record = True
                    print('开始记录鼠标轨迹。')
                else:
                    self.is_start_record = False
                    print('结束记录鼠标轨迹。')
                    file_name = f'ctr_{self.current_index}.txt'
                    file_path = os.path.join(KM_PATH, file_name)
                    with open(file_path, 'w', encoding='utf-8') as f:
                        json.dump(self.ctr, f)
                    print(f'已保存到文件：{file_path}')

        def on_move(x, y):
            if self.is_start_record:
                self.ctr.append(['m', (x, y), time()])

        def on_click(x, y, button, pressed):
            if self.is_start_record:
                self.ctr.append(['c', (x, y), button.name, pressed, time()])

        def on_scroll(x, y, dx, dy):
            if self.is_start_record:
                self.ctr.append(['s', (dx, dy), time()])

        keyboard_listener = keyboard.Listener(on_press=on_press)
        mouse_listener = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)

        # 启动监听器
        keyboard_listener.start()
        mouse_listener.start()

        while True:
            sleep(0.01)

    def control_mouse(self, type_: Literal['', 'double_click', 'drag']):
        pass

    def use_ctr(self, ctr_file_path):
        """
        使用鼠标轨迹文件
        :param ctr_file_path:
        :return:
        """
        with open(ctr_file_path, 'r', encoding='utf-8') as f:
            ctr = json.load(f)





if __name__ == '__main__':
    auto_km = AutoKM()
    auto_km.start_ctr()